package com.example.mvvmtemplate.base.recycler;

import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.view.View;

import androidx.annotation.ColorInt;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

public class DividerItemDecoration extends RecyclerView.ItemDecoration {

    private int topBottom;
    private Paint dividerPaint;

    //使用间隔不使用颜色
    public DividerItemDecoration(int topBottom) {
        this.topBottom = topBottom;
    }

    //使用间隔与用颜色
    public DividerItemDecoration(@ColorInt int color, int topBottom) {
        this.topBottom = topBottom;
        dividerPaint = new Paint();
        dividerPaint.setColor(color);
        dividerPaint.setStyle(Paint.Style.FILL);
    }

    //间隔
    @Override
    public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
        super.getItemOffsets(outRect, view, parent, state);
        outRect.bottom = topBottom;
    }

    //画线
    @Override
    public void onDraw(@NonNull Canvas c, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
        super.onDraw(c, parent, state);
        if (dividerPaint != null) {
            int childCount = parent.getChildCount();
            int left = parent.getPaddingLeft();
            int right = parent.getWidth() - parent.getPaddingRight();

            for (int i = 0; i < childCount - 1; i++) {
                View view = parent.getChildAt(i);
                c.drawRect(left, view.getBottom(), right, view.getBottom() + topBottom, dividerPaint);
            }
        }
    }
}
